package com.StephenHu.controller;

import com.StephenHu.service.ProductService;
import com.StephenHu.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author steph
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService ProductService;

    //显示所有信息
    @RequestMapping("/list")
    public String list(Model model) {
        List<Product> product = ProductService.list();
        model.addAttribute("products", product); // 将产品列表添加到Model中
        return "/list";
    }

    // 增加商品
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addProduct(String name, String parameter, String price, Integer number, String producer, String alert, RedirectAttributes redirectAttrs) {
        Product product = new Product();
        product.setName(name);
        product.setParameter(parameter);
        product.setPrice(price);
        product.setNumber(number);
        product.setProducer(producer);
        product.setAlert(alert);

        boolean isAdded = ProductService.add(product);

        if (isAdded) {
            // 添加成功，使用RedirectAttributes传递成功信息并在重定向后显示
            redirectAttrs.addFlashAttribute("successMessage", "商品添加成功！");
            // 重定向到商品列表页面
            return "redirect:/products/list";
        } else {
            redirectAttrs.addFlashAttribute("errorMessage", "添加商品时发生错误，请重试。");
            return "redirect:/products/add";
        }
    }

    //删除商品
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public boolean deleteTest(Integer id) {
        Product product = new Product();
        product.setId(id);
        return ProductService.delete(product);
    }


}
